package com.springboot.demo.controller;

import com.springboot.demo.entity.UserInfo;
import com.springboot.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * SpringBoot 整合JPA
 * （1）引入起步依赖
 * （2）配置数据源
 * （3）创建实体对象
 * （4）创建DAO层
 * （5）创建service层
 * （6）创建Controller层
 * （7）数据库插入数据： insert into `user_info`(username , password) values('byzhang','111111');
 * （8）测试，浏览器输入地址：  http://localhost:8081/userinfo/byzhang
 */
@RequestMapping("/userinfo")
@RestController
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @ApiOperation(value="用户列表", notes="用户列表")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List<UserInfo> getUserInfos() {
        List<UserInfo> userInfos = userInfoService.findAll();
        return userInfos;
    }

    @ApiOperation(value="创建用户", notes="创建用户")
    @RequestMapping(value="", method=RequestMethod.POST)
    public UserInfo postUser(@RequestBody UserInfo userInfo) {
        return   userInfoService.saveUserInfo(userInfo);

    }

/*    @ApiOperation(value="获用户细信息", notes="根据url的id来获取详细信息")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public UserInfo getUserInfo(@PathVariable Long id) {
        return userInfoService.findUserInfoById(id);
    }*/

    @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
    @RequestMapping(value="/{id}", method= RequestMethod.PUT)
    public UserInfo putUserInfo(@PathVariable Long id, @RequestBody UserInfo userInfo) {
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setUsername(userInfo.getUsername());
        userInfo1.setPassword(userInfo.getPassword());
        userInfo1.setId(id);
        return userInfoService.updateUserInfo(userInfo1);
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUserInfo(@PathVariable Long id) {
        userInfoService.deleteUserInfo(id);
        return "success";
    }

    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }

    @GetMapping("/{username}")
    public UserInfo getUserInfo(@PathVariable("username")String username){
       return userInfoService.findUserInfoByUsername(username);

    }
}
